 package com.fairy.sso.interceptors;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fairy.sso.config.ApiCollection;
import com.fairy.sso.config.FairyConfig;




/**
 * 权限拦截器
 * 
 * @author yyk1504@163.com
 * 
 */
public class AuthInterceptor implements HandlerInterceptor {
	@Autowired
	private FairyConfig config;
	
	
	@Autowired
	private ApiCollection apiCollection;
	
	private static final Logger log = Logger.getLogger(AuthInterceptor.class);
	private List<String> noCheckUrlList;

	public List<String> getNoCheckUrlList() {
		return noCheckUrlList;
	}
	public void setNoCheckUrlList(List<String> noCheckUrlList) {
		this.noCheckUrlList = noCheckUrlList;
	}
	/** 
     * 在业务处理器处理请求之前被调用 
     * 如果返回false 
     *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链 
     *  
     * 如果返回true 
     *    执行下一个拦截器,直到所有的拦截器都执行完毕 
     *    再执行被拦截的Controller 
     *    然后进入拦截器链, 
     *    从最后一个拦截器往回执行所有的postHandle() 
     *    接着再从最后一个拦截器往回执行所有的afterCompletion() 
     */   
	public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
        // TODO Auto-generated method stub  
		HttpSession session=request.getSession();

		String requestUri = request.getRequestURI();
		String contextPath=request.getContextPath();
		//StringBuffer url=request.getRequestURL();
		requestUri=requestUri.replace(contextPath, "");
		//Object userIds=session.getAttribute("userId");
		if(null!=noCheckUrlList&&noCheckUrlList.size()>0)
		{
			//包含在不需要验证的Url列表的Url进程验证
			if (noCheckUrlList.contains(requestUri)) 
			{
				log.info("requestUri is:"+requestUri);
				return true;
			}
			else//需要验证
			{
				return filterAuth(request,response, session, contextPath);
				
			}
		}
		else//需要验证
		{
			return filterAuth(request,response, session, contextPath);
		}
		


    }
	private boolean filterAuth(HttpServletRequest request, HttpServletResponse response, HttpSession session, String contextPath)
			throws IOException {
		@SuppressWarnings("unchecked")
		Map<String,Object>map=(Map<String, Object>) session.getAttribute("session_user");
		//坚持会话
		//Object obj=map.get("userId");
		log.info("obj is:"+map);
		if(null!=map&&!map.isEmpty())//会话保持
		{
			return true;
		}
		else
		{
			/**
    		try{  
    			String requestUri = request.getRequestURI();
    			//String contextPath=request.getContextPath();
    			//StringBuffer url=request.getRequestURL();
    			requestUri=requestUri.replace(contextPath, "");
    			List<String>apiList=apiCollection.getApiList();
    			log.info("访问url is:"+request.getRequestURI());
    			if(apiList.contains(requestUri))//以json形式返回结果
    			{
         		    String no_login_json = config.getNoLoginJson();//properties.getProperty("duplicate_submit_page");
         		   log.info("未登陆，先登录 ,json:"+contextPath+"/"+no_login_json);  
        		    response.sendRedirect(contextPath+"/"+no_login_json);
    			}
    			else
    			{
        			
    			    String no_login_page = config.getNoLoginPage();//properties.getProperty("duplicate_submit_page");
    			    log.info("未登陆，先登录,jsp :"+contextPath+"/"+no_login_page);
    			    response.sendRedirect(contextPath+"/"+no_login_page);
    			}

    		}catch(Exception e){  
    		    e.printStackTrace();  
    		} 
    		*/
    		/*
		    String no_login_page = fairyConfig.getNoLoginPage();//properties.getProperty("duplicate_submit_page");
		    log.info("未登陆，先登录 :"+contextPath+"/"+no_login_page);
		    response.sendRedirect(contextPath+"/"+no_login_page);
		    */
			return false;
		}
	}  

    //在业务处理器处理请求执行完成后,生成视图之前执行的动作   
   
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) throws Exception {   
    }  
  
    /** 
     * 在DispatcherServlet完全处理完请求后被调用  
     *  
     *   当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 
     */    
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex)  
            throws Exception {   
    }

}
